#include "sniffer.h"
#include "packge_handler.h"
#include<QDebug>

Sniffer::Sniffer(){
    pause = true;
    adhandle = nullptr;
}

void Sniffer::run(){
    qDebug("thread start");

    int res;
    struct pcap_pkthdr *header;
    const uchar *pkt_data;


    while(true){
        if(pause) continue;
        res = pcap_next_ex( adhandle, &header, &pkt_data);

        if(res == 0)
          /* Timeout elapsed */
          continue;
        const u_char *data;
        data = (u_char*)malloc(header->len);
        memcpy((char*)(data),pkt_data,header->len);

        emit packge_signal(data,header);


        if(res == -1){
          qDebug("Error reading the packets: %s\n", pcap_geterr(adhandle));
          return ;
        }
    }
}

//切换设备并关闭之前的设备
void Sniffer::set_adhandle(pcap_t *adhandle)
{
    this->adhandle = adhandle;
}

pcap_t *Sniffer::get_adhandle()
{
    return this->adhandle;
}

void Sniffer::pause_sniffer()
{
    pause = true;
}


void Sniffer::start_sniffer()
{
    pause = false;
}
